package cn.wolfcode.service.impl;

import cn.wolfcode.domain.Permission;
import cn.wolfcode.domain.Role;
import cn.wolfcode.mapper.PermissionMapper;
import cn.wolfcode.qo.QueryObject;
import cn.wolfcode.service.IPermissionService;
import cn.wolfcode.util.RequiredPermission;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.mvc.method.RequestMappingInfo;
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyEmitterReturnValueHandler;

import java.util.Collection;
import java.util.List;
import java.util.Map;

@SuppressWarnings("ALL")
@Service
public class PermissionServiceImpl implements IPermissionService {
    @Autowired
    private PermissionMapper permissionMapper;
    @Autowired
    private RequestMappingHandlerMapping handlerMapping;

    @Override
    public List<Permission> selectPermissionList() {
        return permissionMapper.selectAll();
    }


    @Override
    public PageInfo<Permission> query(QueryObject qo) {
        PageHelper.startPage(qo.getCurrentPage(),qo.getPageSize());
        return new PageInfo(permissionMapper.queryList(qo));

    }

    @Override
    public void reload() {
        //先获取所有的expression
        List<String> experessions = permissionMapper.selectExpressionList();
        //通过RequestMappingHandlerMapping获取控制器所有的方法
        Map<RequestMappingInfo, HandlerMethod> handlerMethods = handlerMapping.getHandlerMethods();
        //获取handlerMethods的值
        Collection<HandlerMethod> methods = handlerMethods.values();
        for (HandlerMethod method : methods) {
            //去找贴了RequiredPermission注解的方法
            RequiredPermission permission = method.getMethodAnnotation(RequiredPermission.class);
            //如果RequiredPermission的对象不为空就有贴注解
            if (permission != null){
                String name = permission.name();
                String expression = permission.expression();
                //判断expression是否存过 如果存过就跳过
                if (!experessions.contains(expression)) {
                    Permission p = new Permission();
                    p.setName(name);
                    p.setExpression(expression);
                    permissionMapper.insert(p);
                    experessions.add(expression);
                }
            }
        }
    }
}
